package com.hose.handle;


import com.hose.annotion.CustomProxy;
import com.hose.annotion.EnableRemoteClient;
import com.hose.proxy.ProxyFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Slf4j
@Component("openInstantiationAwareBeanPostProcessor")
public class OpenInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor{

    /**
     * 只用到了实例化前的方法，后面的方法可以不用看了
     * @param beanClass
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {


        //创建任何一个bean对象之前，都会自动调用这个方法，但是我们只对使用了自定义注解的类才创建代理对象，没有使用的直接返回null
        if(!beanClass.isAnnotationPresent(CustomProxy.class)){
            return null;
        }
        log.info("正在为：{}生成代理对象,被代理的类为：{}",beanName,beanClass.getName());
        //动态代理里面需要实现的方法，本文采用的是jdk动态代理
        //实例化每一个bean之前都来判断一下是否有自定义注解，如果有的话就创建代理对象并返回
        Object object = ProxyFactory.createProxy(beanClass);
        return object;

    }

    /**
     * 实例化后
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        return true;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        return pvs;
    }


    /**
     * 初始化前
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * 初始化后
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
